package com.im.partchat.topic;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.im.partchat.App;
import com.im.partchat.R;
import com.im.partchat.topic.bean.BaseResponse;
import com.im.partchat.topic.emoj.EaseEmojicon;
import com.im.partchat.topic.emoj.EaseEmojiconGroupEntity;
import com.im.partchat.topic.tools.HttpUtil;
import com.im.partchat.topic.tools.JsonParser;
import com.im.partchat.topic.widget.AnimationYoYo;
import com.im.partchat.topic.widget.EaseEmojiconMenu;
import com.im.partchat.topic.widget.InputControlEditText;

//发布动态
public class TopicReleaseActivity extends BasePhotoGridActivity implements
		InputControlEditText.InputLengthHintListener, InputControlEditText.GetInputLengthListener {
	public final static int RELEASE_SUCCESS = 0x23;
	private InputControlEditText content_et;

	private TextView showlength_tv;
	private final int maxlength = 300;

	private CheckBox location_checkbox;
	private FrameLayout emojiconMenuContainer;
	private ImageView  face_btn;
	

	private MyHandler handler = new MyHandler(this);
	private static class MyHandler extends Handler {
		
		private WeakReference<Context> reference;
		
	    public MyHandler(Context context) {
	    	reference = new WeakReference<Context>(context);
	    }
	    
	    @Override
		public void handleMessage(Message msg) {
	    	final TopicReleaseActivity activity = (TopicReleaseActivity) reference.get();
			if(activity == null){
				return;
			}
			activity.progress.dismiss();

			switch (msg.what) {
			case NETWORK_SUCCESS_DATA_RIGHT:
				BaseResponse retMap = (BaseResponse) msg.obj;
				if (retMap.isSuccess()) {
					activity.hideKeyboard();
					activity.setResult(RELEASE_SUCCESS);
					activity.finish();
				} else {
					activity.showErrorToast(retMap.getMessage());
				}
				break;
			default:
				activity.showErrorToast("发布失败");
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_release);
		initView();
		initListener();
	}

	protected void initView() {
		// TODO Auto-generated method stub
		super.initView();
		
		location_checkbox = (CheckBox)findViewById(R.id.location_checkbox);
		face_btn = (ImageView) findViewById(R.id.face_btn);
		content_et = (InputControlEditText) findViewById(R.id.content_et);
		showlength_tv = (TextView) findViewById(R.id.showLength);
		content_et.setOnKeyListener(new View.OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER
						&& event.getAction() == KeyEvent.ACTION_DOWN) {
					// doneClick();
					return true;
				}
				return false;
			}
		});

		content_et.setOnMaxInputListener(maxlength, this);

		content_et.setOnGetInputLengthListener(this);

		setShowLength(maxlength);

		emojiconMenuContainer = (FrameLayout) findViewById(R.id.emojicon_menu_container);
		// 表情栏，只添加小表情
		EaseEmojiconMenu emojiconMenu = (EaseEmojiconMenu) LayoutInflater.from(this).inflate(R.layout.ease_layout_emojicon_menu, null);
		List<EaseEmojiconGroupEntity> emojiconGroupList = new ArrayList<EaseEmojiconGroupEntity>();

		emojiconGroupList.add(new EaseEmojiconGroupEntity(
				R.drawable.expression_1, App
						.getFaceManager().getEmojiconList()));
		((EaseEmojiconMenu) emojiconMenu).init(emojiconGroupList);
		emojiconMenuContainer.addView(emojiconMenu);

		emojiconMenu.setEmojiconMenuListener(new EaseEmojiconMenu.EaseEmojiconMenuListener() {
			
			@Override
			public void onExpressionClicked(EaseEmojicon emojicon) {
				// TODO Auto-generated method stub
				content_et.insertEmotion(TopicReleaseActivity.this, emojicon);
			}
			
			@Override
			public void onDeleteImageClicked() {
				// TODO Auto-generated method stub
				content_et.onEmojiconDeleteEvent();
			}
		});
		

		Handler hander = new Handler();
		hander.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				showKeyboard(content_et);
			}
		}, 150);
	}

	private void initListener() {
//		findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
//
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				hideKeyboard();
//				finish();
//			}
//		});
		findViewById(R.id.title_right).setOnClickListener(
				new View.OnClickListener() {

					public void onClick(View v) {
						// TODO Auto-generated method stub
							doneClick();
					}
				});
		content_et.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				showKeyboard(content_et);
				emojiconMenuContainer.setVisibility(View.GONE);
				face_btn.setImageResource(R.drawable.compose_emoticonbutton_background_highlighted);
				return false;
			}
		});
		face_btn.setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (emojiconMenuContainer.getVisibility() != View.VISIBLE) {
							hideKeyboard();
							emojiconMenuContainer.setVisibility(View.VISIBLE);
							((ImageView)v).setImageResource(R.drawable.compose_keyboardbutton_background_highlighted);
						} else {
							showKeyboard(content_et);
							emojiconMenuContainer.setVisibility(View.GONE);
							((ImageView)v).setImageResource(R.drawable.compose_emoticonbutton_background_highlighted);
						}
					}
				});
		findViewById(R.id.gallery_btn).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showBottomPopupWin();
			}
		});
	}

	private void doneClick() {
		if (content_et.getText().toString().trim().equals("")) {
			AnimationYoYo.shakeView(findViewById(R.id.content_et));
			return;
		}
		progress.show();
		new Thread(new UpdateImagesRun(thumbPictures)).start();
	}

	// 一次HTTP请求上传多张图片 + 各种参数
	private class UpdateImagesRun implements Runnable {
		private ArrayList<String> thumbPictures;

		// thumbPictures 是 List<压缩图路径>
		public UpdateImagesRun(ArrayList<String> thumbPictures) {
			this.thumbPictures = new ArrayList<String>();
			for (String string : thumbPictures) {
				if (!string.equals(""+BasePhotoGridActivity.PICTURE_UPDATE_ICON)) {
					//去掉最后一个 +图片
					this.thumbPictures.add(string);
				}
			}
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			BaseResponse response = null;
			try {
				HashMap<String, String> data = new HashMap<String, String>();
				data.put("userid", App.getUserBean().getId());
				data.put("content", content_et.getText().toString().trim());
				data.put("address", location_checkbox.isChecked()?location_checkbox.getText().toString(): "来自 "+android.os.Build.MODEL);

				// 一次http请求将所有图片+参数上传
				response = JsonParser.getBaseResponse(HttpUtil.upload(data, thumbPictures,HttpUtil.IP + "topic/release"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (response != null) {
				handler.sendMessage(handler.obtainMessage(
						BaseActivity.NETWORK_SUCCESS_DATA_RIGHT, response));
			} else {
				handler.sendEmptyMessage(BaseActivity.NETWORK_FAIL);
			}
		}
	}
	
	private void setShowLength(int requestCode) {
		int currentLength = content_et.getText().length();
		setShowTextLength(currentLength, maxlength);
	}

	@Override
	public void getInputLength(int length) {
		setShowTextLength(length, maxlength);
	}

	private void setShowTextLength(int currentLength, int maxLength) {
		showlength_tv.setText(currentLength + "/" + maxLength + " 字");
	}

	@Override
	public void onOverFlowHint() {
		// TODO Auto-generated method stub
		AnimationYoYo.shakeView(showlength_tv);
	}



	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (getCurrentFocus() != null) {
			((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(
							getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		hideKeyboard();
		emojiconMenuContainer.setVisibility(View.GONE);
		super.onPause();
	}

}
